import {Http} from "@angular/http";
import {Constant} from "./constant";
import {Query, Rsp} from "./model";
import {Toast} from "./util";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import "rxjs/add/operator/catch";
import "rxjs/add/operator/map";
import {NavController} from "ionic-angular";
import {LoginPage} from "../../pages/login/login";

@Injectable()
export class HttpClient {
  rsp: Rsp;

  constructor(private http: Http, private toast: Toast, private navCtrl: NavController) {
  }

  get(url: string, params?: URLSearchParams): Observable<any> {
    return this.http.get(Constant.HTTP_URL + url + Constant.TOKEN_KEY, {search: params}).map(res => {
      this.rsp = res.json();
      this.rsp.isOk = this.rsp.code == 1;
      if (!this.rsp.isOk) {
        this.toast.show(this.rsp.msg);
        if (this.rsp.msg == '用户已失效，请重新登录') {
          this.navCtrl.popAll();
          this.navCtrl.push(LoginPage);
        }
      }
      return this.rsp.data;
    });
  }

  query(url: string, query: Query): Observable<any> {
    let params = new URLSearchParams();
    params.append('page', query.page.toString());
    params.append('size', query.size.toString());
    return this.get(url, params);
  }

  post(url: string, body?: any): Observable<any> {
    return this.http.post(Constant.HTTP_URL + url + Constant.TOKEN_KEY, body).map(res => {
      this.rsp = res.json();
      this.rsp.isOk = this.rsp.code == 1;
      if (!this.rsp.isOk) {
        this.toast.show(this.rsp.msg);
        if (this.rsp.msg == '用户已失效，请重新登录') {
          this.navCtrl.popAll();
          this.navCtrl.push(LoginPage);
        }
      }
      return this.rsp;
    });
  }


}
